package com.my.aslife.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.my.aslife.mapper.ConsultMapper;
import com.my.aslife.mapper.UserMapper;
import com.my.aslife.module.common.*;
import com.my.aslife.module.entity.Consult;
import com.my.aslife.module.entity.Orders;
import com.my.aslife.module.entity.User;
import com.my.aslife.module.entity.dtos.ConsultCommitDto;
import com.my.aslife.service.ConsultService;
import com.my.aslife.service.IUserService;
import com.my.aslife.utils.Code;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author mayuan
 * @description TODO
 */
@Service
@Slf4j
public class ConsultServiceImpl extends ServiceImpl<ConsultMapper, Consult> implements ConsultService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private IUserService userService;


    @Override
    public ResponseResult commitConsult(ConsultCommitDto consultCommitDto) {

        Long uid = consultCommitDto.getUid();
        String key = RedisConstant.USER_CONSULT_ORDER + consultCommitDto.getOrderId() +"-" + uid;
        String consultFlag = stringRedisTemplate.opsForValue().get(key);
        // 已经提交了协商意见
        if (consultFlag != null) {
            return ResponseResult.failed(ErrorCode.CONSULT_IS_COMMITTED);
        }
        stringRedisTemplate.opsForValue().set(key, String.valueOf(System.currentTimeMillis()));

        Consult queryConsultByOrderId = queryConsultByOrderId(consultCommitDto.getOrderId());
        Consult consult = new Consult();
        if (consultCommitDto.getType() == 0) {
            consult.setUserId(uid);
        }
        if (consultCommitDto.getType() == 1) {
            consult.setRunnerId(uid);
        }
        consult.setOrderId(consultCommitDto.getOrderId());

        if (queryConsultByOrderId == null) {
            consult.setCreateTime(new Date());
            save(consult);
        } else {
            updateById(queryConsultByOrderId);
        }

        return ResponseResult.ok();
    }

    @Override
    public Consult queryConsultByOrderId(Long orderId) {
        LambdaQueryWrapper<Consult> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Consult::getOrderId, orderId);
        return getOne(lqw);
    }

    @Override
    public ResponseResult selectOrderInfoByPageOrCondition(PageRequestVo pageRequestVo) {
        int c = pageRequestVo.getCurrent();
        int size = pageRequestVo.getPageSize();
        int start = (c - 1) * size;

        Page<Consult> page = new Page<>(pageRequestVo.getCurrent(), pageRequestVo.getPageSize());
        Page<Consult> page1 = page(page);
        List<Consult> records = page1.getRecords();

        return ResponseResult.ok(records, count());
    }

    /**
     * 注入邮件工具类
     */
    @Autowired
    private JavaMailSenderImpl javaMailSender;

    @Value("${spring.mail.username}")
    private String sendMailer;

    @Override
    public ResponseResult sendEmail(Integer id) {

        Consult byId = getById(id);
        String to = "";
        if (byId.getUserId() != null) {
            ResponseResult responseResult = userService.queryUserInfoByUID(byId.getUserId());
            User user = (User)responseResult.getData();
            if (user.getEmail() != null) {
                to = user.getEmail() + ',';
            }

        }

        if (byId.getRunnerId() != null) {
            ResponseResult responseResult = userService.queryUserInfoByUID(byId.getRunnerId());
            User user = (User)responseResult.getData();
            if (user.getEmail() != null) {
                if (to.length() < 1) {
                    to = user.getEmail();
                } else {
                    to += user.getEmail();
                }
            }
        }


        /** 发送主题*/
        String subject = "阿师跑腿";
        // 获取 6 位验证码
        String code = Code.getCode();
        // 发送文本内容
        String text = "【阿师跑腿】 您的订单已发起协商处理，请加管理员微信号：13778250175，并备注订单号：" + byId.getOrderId();
        try {
            //true 代表支持复杂的类型
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(javaMailSender.createMimeMessage(),true);
            //邮件发信人
            mimeMessageHelper.setFrom(sendMailer);
            //邮件收信人  1或多个
            mimeMessageHelper.setTo(to.split(","));
            //邮件主题
            mimeMessageHelper.setSubject(subject);
            //邮件内容
            mimeMessageHelper.setText(text);
            //邮件发送时间
            mimeMessageHelper.setSentDate(new Date());
            //发送邮件
            javaMailSender.send(mimeMessageHelper.getMimeMessage());
            log.info("发送邮件成功：{} -> {}",sendMailer, to);

        } catch (MessagingException e) {
            log.error("发送邮件失败：{}",e.getMessage());
        }
        return null;
    }
}
